# 每日定时启动客户端
import pandas as pd
import os,log
import pyautogui, psutil, sys
import pyscreeze, cv2

import webbrowser
import subprocess,time




# 杀掉指定进程名的进程ID
def kill(proc_pid):
    process = psutil.Process(proc_pid)
    for proc in process.children(recursive=True):
        proc.kill()
        process.kill()


# 获取指定进程名的进程ID
def get_pid_by_name(process_name):
    for proc in psutil.process_iter(['pid', 'name']):
        if proc.info['name'] == process_name:
            return proc.info['pid']
    return None






#  图片识别点击控件
def getButton(targetImage):
    # 屏幕缩放系数 mac缩放是2 windows一般是1
    screenScale = 1
    # 事先读取按钮截图
    target = cv2.imread(targetImage, cv2.IMREAD_GRAYSCALE)
    # 先截图
    screenshot = pyscreeze.screenshot('my_screenshot.png')
    # 读取图片 灰色会快
    temp = cv2.imread(r'my_screenshot.png', cv2.IMREAD_GRAYSCALE)
    theight, twidth = target.shape[:2]
    tempheight, tempwidth = temp.shape[:2]
    # 先缩放屏幕截图 INTER_LINEAR INTER_AREA
    scaleTemp = cv2.resize(temp, (int(tempwidth / screenScale), int(tempheight / screenScale)))
    stempheight, stempwidth = scaleTemp.shape[:2]
    # 匹配图片
    res = cv2.matchTemplate(scaleTemp, target, cv2.TM_CCOEFF_NORMED)
    mn_val, max_val, min_loc, max_loc = cv2.minMaxLoc(res)
    if (max_val >= 0.9):
        # 计算出中心点
        top_left = max_loc
        bottom_right = (top_left[0] + twidth, top_left[1] + theight)
        tagHalfW = int(twidth / 2)
        tagHalfH = int(theight / 2)
        tagCenterX = top_left[0] + tagHalfW
        tagCenterY = top_left[1] + tagHalfH
        # 左键点击屏幕上的这个位置
        pyautogui.doubleClick(tagCenterX, tagCenterY)
    else:
        print("没找到")
        # log.info(f"没找到图片{targetImage}")

#   自动点击客户端菜单
def getAutoOutput(actionList):
    for actionRPA in actionList:
        if actionRPA == 'enter':
            pyautogui.press('enter')
            time.sleep(2)
        elif actionRPA[0:3] == 'tab':
            for i in range(int(actionRPA[3])):
                pyautogui.press('tab')
            time.sleep(2)
        elif actionRPA == 'shift':
            pyautogui.press('shift')
            time.sleep(2)
        elif actionRPA.find('.png')!=-1:
            getButton(actionRPA)
            time.sleep(5)
        elif actionRPA == '切换输入法':
            pyautogui.hotkey('ctrl', 'space')
            time.sleep(2)
        elif actionRPA == '显示桌面':
            pyautogui.hotkey('win','d')
            time.sleep(2)
        else:
            pyautogui.write(actionRPA)



是否测试=True
beginPath = os.path.dirname(os.path.realpath(sys.argv[0]))

if 是否测试==True:
    运行清单 = os.path.join(beginPath, "autoStartTest.csv")
    浏览器类型="chrome"
    webbrowser.register('chrome', None,webbrowser.BackgroundBrowser(r"C:\Program Files\Google\Chrome\Application\chrome.exe"))
    # 关闭掉浏览器
    for proc in psutil.process_iter():
        try:
            if proc.name() == "chrome.exe":
                os.system(r'taskkill /F /IM {}'.format("chrome.exe"))
                print("已踢掉程序chrome.exe")
        except (psutil.NoSuchProcess, psutil.AccessDenied, psutil.ZombieProcess):
            pass
else:
    运行清单 = os.path.join(beginPath, "autoStart.csv")
    浏览器类型="edge"
    webbrowser.register('edge', None,webbrowser.BackgroundBrowser(r"C:\Program Files (x86)\Microsoft\Edge\Application\msedge.exe"))
    # 关闭掉浏览器
    for proc in psutil.process_iter():
        try:
            if proc.name() == "msedge.exe":
                os.system(r'taskkill /F /IM {}'.format("msedge.exe"))
                print("已踢掉程序msedge.exe")
        except (psutil.NoSuchProcess, psutil.AccessDenied, psutil.ZombieProcess):
            pass
configData = pd.read_csv(运行清单)
start_time = configData["启动时间(需要同一个时间)"].iloc[0]

indexconfig = len(configData)
启动程序等待时间=5
# 是否重启浏览器=False
# time.sleep(3)
def start_client():

    for i in range(indexconfig):
        client = configData["系统"].iloc[i]
        clientPath = configData["客户端exe目录"].iloc[i]
        userName = configData["账号"].iloc[i]
        password = configData["密码"].iloc[i]
        processName = configData["进程名称"].iloc[i]
        窗口名称=configData["程序窗口名称"].iloc[i]
        是否启动=configData["是否启动"].iloc[i]
        for proc in psutil.process_iter():
            try:
                if proc.name() == processName:
                    os.system(r'taskkill /F /IM {}'.format(processName))
                    print(f"已踢掉程序{processName}")
            except (psutil.NoSuchProcess, psutil.AccessDenied, psutil.ZombieProcess):
                pass


        if clientPath.startswith("http") and 是否启动=="Y":

            webbrowser.get(using=浏览器类型).open_new_tab(clientPath)   #新开标签页
        else:
            if 是否启动=="Y":
                print(clientPath)
                if client!="OneQuant":
                    # 显示桌面()
                    os.system(' start cmd.exe /K \"C:\\Program File（x86）\\ISEP\\bin\\unins.exe\" ')

                    os.startfile(clientPath)
                    time.sleep(10)
        if client == "OneQuant" and 是否启动=="Y":
            print(f"开始登录操作{client}")
            启动路标路径=os.path.join(beginPath,"OQexe.png")
            print(启动路标路径)
            getAutoOutput(["显示桌面",启动路标路径,'tab2','切换输入法', userName, 'tab1', password, 'enter'])
            time.sleep(启动程序等待时间)
        elif client == "手工T0" and 是否启动=="Y":
            print(f"开始登录操作{client}")
            getAutoOutput(['tab1', "tab1",'切换输入法', userName, 'tab1', password, 'enter'])
            time.sleep(启动程序等待时间)
        elif client == "恒生PB" and 是否启动=="Y":
            print(f"开始登录操作{client}")
            getAutoOutput(['tab4','切换输入法', userName, 'tab1', password, 'enter'])
            time.sleep(启动程序等待时间)
        elif client == "OQtest" and 是否启动=="Y":
            print(f"开始登录操作{client}")
            getAutoOutput(['tab2','切换输入法', userName, 'tab1', password, 'enter'])
            time.sleep(启动程序等待时间)
        elif client == "Ptrade" and 是否启动=="Y":
            print(f"开始登录操作{client}")
            getAutoOutput(['tab9','切换输入法', userName, 'tab1', password, 'enter'])
            time.sleep(启动程序等待时间*5)
        elif client == "络町PB" and 是否启动=="Y":
            print(f"开始登录操作{client}")
            getAutoOutput(["enter", 'tab2','切换输入法', userName, 'tab1', password, 'enter'])
            time.sleep(启动程序等待时间*5)
        elif client == "迅投PB" and 是否启动=="Y":
            print(f"开始登录操作{client}")
            getAutoOutput(['切换输入法',userName, 'tab1', password, 'enter'])
            time.sleep(启动程序等待时间*5)
        elif client == "宏汇ETF" and 是否启动=="Y":
            print(f"开始登录操作{client}")
            启动路标路径=os.path.join(beginPath,"jingu.png")
            getAutoOutput([启动路标路径,'切换输入法', userName, 'tab1', password, 'enter'])
            time.sleep(启动程序等待时间*1)
        elif client == "今古ETF" and 是否启动=="Y":
            print(f"开始登录操作{client}")
            启动路标路径=os.path.join(beginPath,"honghui.png")
            getAutoOutput([启动路标路径,'切换输入法',userName, 'tab2', password, 'enter'])
            time.sleep(启动程序等待时间*1)
        elif client == "聚安一站通" and 是否启动=="Y":
            print(f"开始登录操作{client}")
            启动路标路径=os.path.join(beginPath,"juan.png")
            getAutoOutput([启动路标路径,'切换输入法',userName, 'tab1', password, 'enter'])
            time.sleep(启动程序等待时间*1)
start_client()




# 定时轮询启动任务
# while True:
#     if 是否测试==False:
#         if time.localtime().tm_hour == int(str(start_time).split(":")[0]) and time.localtime().tm_hour == int(str(start_time).split(":")[2]) and 启动标识 == False:
#             是否重启浏览器=False
#             start_client()
#             time.sleep(60)
#         else:
#             # print("未到定时启动时间")
#             pass
#     elif 是否测试==True:
#         if time.localtime().tm_hour > int(str(start_time).split(":")[0]) and  启动标识 == False:
#             是否重启浏览器=False
#             start_client()
#             time.sleep(60)
#         else:
#             print("未到定时启动时间")
#             # pass




